package com.tjetc.proxy;


import com.zhiyun.vo.AppData;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class CilentProxy {
    public static <T> T getProxyInstance(Class clz){
        return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                System.out.println(clz.getSimpleName());//接口名
//                System.out.println(method.getName());//方法名
//                System.out.println(Arrays.toString(method.getParameterTypes()));//方法的参数类型
//                System.out.println(Arrays.toString(args));//实参
                Socket socket = new Socket(AppData.ServerIp, AppData.ServerPort);
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                outputStream.writeUTF(clz.getSimpleName());
                outputStream.writeUTF(method.getName());
                outputStream.writeObject(method.getParameterTypes());
                outputStream.writeObject(args);
                outputStream.flush();
                Object o = inputStream.readObject();

                return o;
            }
        });
    }
}
